import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:myapp/app/data/repository/comm_repository.dart';
import 'package:myapp/app/data/user_manager.dart';
import 'package:myapp/app/routes/app_pages.dart';

class EntranceController extends GetxController {

  final _commRepository = Get.find<CommRepository>();

  var countDown = 0.0.obs;
  final step = 50;
  late Timer _timer;
  var percent = 0.0;

  bool _loading = true;

  @override
  void onInit() {
    super.onInit();
    percent = step / 2000.0;
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  @override
  void onClose() {
    _timer.cancel();
  }

  void _initData() async {
    try {
      var token = _commRepository.getToken();
      print("_initData token $token");
      if(token == null) {
        token = await _commRepository.deviceRegister();
      } else {
        _commRepository.loadLocalUser();
        //如果已经登录过，使用token自动登录
        print("_initData isLogin ${UserManager.instance.isLogin}");
        if(UserManager.instance.isLogin) {
          var user = await _commRepository.tokenLogin();
        }
      }
    } catch(e) {
      print("_initData $e");
    }
    _loading = false;
    _calc();
  }

  void pass() {
    if(_loading) {
      Get.showSnackbar(GetBar(message: "数据加载中...",));
      return;
    }
    _jump2Page();
  }
  
  void _jump2Page() {
    if(UserManager.instance.isLogin) {
      //跳转首页
      Get.offAndToNamed(Routes.HOME);
      return;
    }
    //跳转login页面
    Get.offAndToNamed(Routes.LOGIN);
  }

  void _calc() {
    //每 50毫秒调用一次
    _timer = Timer.periodic(Duration(milliseconds: step), (timer) {
      print("_timer $countDown");
      if (countDown.value > 1) {
        print("_timer 退出");
        _timer.cancel();
        //加载完成
        _jump2Page();
      }
      countDown.value += percent;
      print("_timer ${countDown}");
    });
  }
}
